package com.hc.model.code02.test12;

import java.io.*;

/**
 * @version v1.0
 * @ClassName: DeepClone
 * @Description: 深克隆实现
 * @Author: HC
 */
public class DeepClone {


    public static void main(String[] args) throws Exception {
        // 浅克隆测试缺点
        // 内部对象引用地址没新建
//        shallow();
        // 深克隆测试
        // 通过序列化方式
        deep();
    }

    private static void deep() throws Exception {
        User user = new User();
        Student s = new Student();
        s.setName("张三");
        user.setStudent(s);
        // 创建输出流对象 写入对象
        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("D://a.txt"));
        oos.writeObject(user);
        oos.close();
        // 创建输入流对象 读取对象
        ObjectInputStream ois = new ObjectInputStream(new FileInputStream("D://a.txt"));
        User user1 = (User) ois.readObject();
        oos.close();
        user1.getStudent().setName("李四");
        System.out.println(user.getStudent().getName());
        System.out.println(user1.getStudent().getName());
    }

    private static void shallow() throws Exception {
        User user = new User();
        Student s = new Student();
        s.setName("张三");
        user.setStudent(s);
        // 克隆新对象
        User user1 = user.clone();
        // 给新对象复制
        user1.getStudent().setName("李四");
        // 判断对象值发生了什么变化
        System.out.println(user.getStudent().getName());
        System.out.println(user1.getStudent().getName());
    }
}
